package top.wuyang.study.java24.servlet.dept;

import top.wuyang.study.java24.dao.TbDeptDAO;
import top.wuyang.study.java24.entity.Result;
import top.wuyang.study.java24.entity.TbDept;
import top.wuyang.study.java24.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "deptinsertservlet", urlPatterns = "/dept/insert.action")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        try {
            String dept_name = req.getParameter("dept_name");
            String description = req.getParameter("description");
            // 部门名称检测
            TbDept check = TbDeptDAO.queryByName(dept_name);
            if (check!=null){
                Result<String> result = Result.fail("部门已存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            check = new TbDept();
            check.setDept_name(dept_name);
            check.setDescription(description);
            int i = TbDeptDAO.insert(check);
            if (i==1){
                Result<String> result = Result.success("添加成功", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            Result<String> result = Result.fail("添加失败", null);
            writer.println(JsonUtils.stringify(result));
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }
}
